package org.atlantis.uzw.utils;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * 异常工具类
 * 
 * @author <a href="mailto:seenoevil.cn@gmail.com">李曦</a><br/>
 *         Created at: 2013-7-29 下午5:54:04
 */
public class Exceptions {

	/**
	 * 将CheckedException转换为UncheckedException.
	 */
	public static RuntimeException unchecked(Exception e) {
		if (e instanceof RuntimeException) {
			return (RuntimeException) e;
		}
		return new RuntimeException(e);
	}

	/**
	 * 将异常栈转换为String
	 */
	public static String getStackTraceAsString(Exception e) {
		StringWriter stringWriter = new StringWriter();
		e.printStackTrace(new PrintWriter(stringWriter));
		return stringWriter.toString();
	}

	/**
	 * 判断异常e是否是由指定causedExceptions所引发的
	 */
	@SuppressWarnings("unchecked")
	public static boolean isCausedBy(Exception e, Class<? extends Exception>... causedExceptions) {
		Throwable cause = e;
		while (cause != null) {
			for (Class<? extends Exception> causedException : causedExceptions) {
				if (causedException.isInstance(cause)) return true;
			}
		}
		return false;
	}
}
